using Microsoft.AspNetCore.Mvc;
using server.Services;
using server.Models;
using Microsoft.EntityFrameworkCore;

namespace server.Controllers;

[ApiController]
[Route("api/[controller]")]
public class IdentityController : ControllerBase
{
    private LibraryContext db;
    private TokenService tokenService;
    public IdentityController(LibraryContext db, TokenService tokenService)
    {
        this.db = db;
        this.tokenService = tokenService;
    }
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginRequest loginRequest)
    {
        System.Console.WriteLine("user:{0}", loginRequest.Nickname);
        var users = db.Users.Include(u => u.Role).Where(u => u.NickName == loginRequest.Nickname.Trim()).AsNoTracking().ToArray();
        if (users is null || users.Length == 0)
        {
            return NotFound("User not found!");
        }
        foreach (var user in users)
        {
            if (user.Password == loginRequest.Password)
            {
                System.Console.WriteLine("Find User:{0}", user.Name);
                var token = tokenService.GetOrCreateToken(user);
                // var option = new CookieOptions();
                // option.MaxAge = token.MaxAge;
                // HttpContext.Response.Cookies.Append("X-Token", token.ID.ToString(), option);
                return Ok(new LoginResponse { ID = user.ID, Token = token.ID.ToString(), NickName = user.NickName, Role = user.Role.Name });
            }
        }
        return BadRequest("Invalid password!");
    }

    [HttpGet("logout")]
    public IActionResult Logout()
    {
        // var flag = tokenService.RemoveToken(HttpContext);
        return Ok();
    }

    private IActionResult Forbid403(object? value)
    {
        return StatusCode(403, value);
    }
}